package com.find.memories.gallery;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.find.memories.ApplicationPool;
import com.find.memories.R;
import com.find.memories.cache.ImageCache;
import com.find.memories.cache.ImageFetcher2;
import com.find.memories.photoviewer.PhotoViewerActivity;

public class FragmentGalleryAdapter extends BaseAdapter{
    private static final String IMAGE_CACHE_DIR = "thumbs";
    
    private final Context mContext;
    private int mItemHeight = 0;
    private int mNumColumns = 0;
    private int mActionBarHeight = 0;
    private GridView.LayoutParams mImageViewLayoutParams;
    private ArrayList<PhotoItem> mItems = new ArrayList<PhotoItem>();

    ImageFetcher2 mImageFetcher;
    
    public FragmentGalleryAdapter(Context context, ArrayList<PhotoItem> items) {
        super();
        mContext = context;
        mItems = items;
        
        mImageViewLayoutParams = new GridView.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        // Calculate ActionBar height
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(
                android.R.attr.actionBarSize, tv, true)) {
            mActionBarHeight = TypedValue.complexToDimensionPixelSize(
                    tv.data, context.getResources().getDisplayMetrics());
        }
        
        ImageCache.ImageCacheParams cacheParams =
                new ImageCache.ImageCacheParams(mContext, IMAGE_CACHE_DIR);

        cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

        Display dis = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();   
        int imageSize = dis.getWidth() / 3; 

        // The ImageFetcher takes care of loading images into our ImageView children asynchronously
        mImageFetcher = new ImageFetcher2(mContext, imageSize);
        mImageFetcher.addImageCache(cacheParams);
        
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
    }

    @Override
    public int getCount() {
//        return mItems.size() + mNumColumns;
        return mItems.size();
    }

    @Override
    public Object getItem(int position) {
//        return position < mNumColumns ?
//                null : mItems.get(position- mNumColumns);
        return mItems.get(position);
    }

    @Override
    public long getItemId(int position) {
//        return position < mNumColumns ? 0 : position - mNumColumns;
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        // Two types of views, the normal ImageView and the top row of empty views
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        return (position < mNumColumns) ? 1 : 0;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        //BEGIN_INCLUDE(load_gridview_item)
        // First check if this is the top row
//        if (position < mNumColumns) {
//            if (convertView == null) {
//                convertView = new View(mContext);
//            }
//            // Set empty view with height of ActionBar
//            convertView.setLayoutParams(new AbsListView.LayoutParams(
//                    LayoutParams.MATCH_PARENT, mActionBarHeight));
//            return convertView;
//        }

        // test
        // Now handle the main ImageView thumbnails
//        ImageView imageView;
//        if (convertView == null) { // if it's not recycled, instantiate and initialize
//            imageView = new RecyclingImageView(mContext);
//            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//            imageView.setLayoutParams(mImageViewLayoutParams);
//        } else { // Otherwise re-use the converted view
//            imageView = (ImageView) convertView;
//        }
//
//        // Check the height matches our calculated column width
//        if (imageView.getLayoutParams().height != mItemHeight) {
//            imageView.setLayoutParams(mImageViewLayoutParams);
//        }
//
//        // Finally load the image asynchronously into the ImageView, this also takes care of
//        // setting a placeholder image while the background thread runs
//        mImageFetcher.loadImage(Images.imageThumbUrls[position - mNumColumns], imageView);
//        return imageView;
        ImageView imageView;
        
        if (convertView == null) {
            imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(mImageViewLayoutParams);
        } else {
            imageView = (ImageView) convertView;
        }
        
        final int index = position;
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, PhotoViewerActivity.class);
                intent.putExtra(PhotoViewerActivity.START_POSITION, index);
                ApplicationPool pool = (ApplicationPool)mContext.getApplicationContext();
                pool.putExtra(PhotoViewerActivity.KEY_DATA_LIST, intent, mItems);
                mContext.startActivity(intent);
            }
        });
        
        if (imageView.getLayoutParams().height != mItemHeight) {
            imageView.setLayoutParams(mImageViewLayoutParams);
        }
        
        PhotoItem photoItem = mItems.get(position);
        
        mImageFetcher.loadImage(photoItem.data, imageView);
//        Bitmap bitmap = Utils.getThumnailImg(mContext.getContentResolver(), photoItem);
//        imageView.setImageBitmap(bitmap);
        
        return imageView;
        //END_INCLUDE(load_gridview_item)
    }

    public void setItems(ArrayList<PhotoItem> items) {
        mItems.clear();
        mItems = items;
        notifyDataSetChanged();
    }
    
    /**
     * Sets the item height. Useful for when we know the column width so the height can be set
     * to match.
     *
     * @param height
     */
    public void setItemHeight(int height) {
        if (height == mItemHeight) {
            return;
        }
        mItemHeight = height;
        mImageViewLayoutParams =
                new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
        // test
//        mImageFetcher.setImageSize(height);
        notifyDataSetChanged();
    }

    public void setNumColumns(int numColumns) {
        mNumColumns = numColumns;
    }

    public int getNumColumns() {
        return mNumColumns;
    }
}

